import {messages} from "share/common";
import React from 'react';
import {Select, Icon, Popover} from 'antd'
import SelectDepartment from 'components/template/select-department'
import 'styles/components/chooser.scss'

class DepartmentPicker extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      value: [],
      selectedList: [],
      showListSelector: false,
      listSelectedData: []
    };
  }

  componentWillMount() {
    this.setValue(this.props.value);
  }

  setValue = (valueWillSet) => {
    if (valueWillSet &&
      typeof valueWillSet !== 'string' && //onlyNeed模式下返回的single值
      !(valueWillSet.splice && valueWillSet.length > 0 && typeof valueWillSet[0] === 'string')  //onlyNeed模式下返回的只有需要值数组
    ) {
      let lengthChange = valueWillSet.length !== this.state.value.length;
      let innerChange = false;
      if (valueWillSet.length === this.state.value.length) {
        valueWillSet.map((nextItem, index) => {
          innerChange = innerChange || this.state.value[index].key !== nextItem.value;
        })
      }
      if (lengthChange || innerChange) {
        let values = [];
        valueWillSet.map(item => {
          values.push({
            label: item.label,
            key: item.value,
            value: item
          })
        });
        this.setState({value: values, selectedList: values});
        this.onChange(valueWillSet);
      }
    }
    if ((!valueWillSet && this.state.value.length > 0) || (valueWillSet && valueWillSet.length === 0 && this.state.value.length > 0)) {
      this.setState({value: []})
    }
  };

  /**
   * value为传入值
   * @param nextProps
   */
  componentWillReceiveProps = (nextProps) => {
    this.setValue(nextProps.value)
  };

  /**
   * list控件因为select没有onClick事件，所以用onFocus代替
   * 每次focus后，用一个隐藏的input来取消聚焦
   */
  handleFocus = () => {
    this.refs.chooserBlur.focus();
    this.showList()
  };

  /**
   * 显示ListSelector，如果有已经选择的值则包装为ListSelector需要的默认值格式传入
   */
  showList = () => {
    let listSelectedData = [];
    if (this.state.value.length > 0) {
      this.state.value.map(value => {
        listSelectedData.push(value.value)
      });
    }
    this.setState({listSelectedData}, () => {
      this.setState({showListSelector: true})
    })
  };

  handleListCancel = () => {
    this.setState({showListSelector: false})
  };

  /**
   * ListSelector确认点击事件，返回的结果包装为form需要的格式
   * @param result
   */
  handleListOk = (result) => {
    let value = [];
    result.checkedKeys.map(item => {
      value.push({
        label: item.label,
        key: item.value,
        value: item
      })
    });
    //手动调用onChange事件以与父级Form绑定
    this.setState({showListSelector: false, value, selectedList: result.checkedKeys},() => {
      this.onChange(result.checkedKeys);
    });
  };

  clear = () => {
    this.onChange([]);
    this.setState({value: []})
  };

  onChange = (changedValue) => {
    const {onChange} = this.props;
    if (onChange) {
      onChange(changedValue);
    }
  };


  render() {
    const {showListSelector, value, selectedList} = this.state;
    const {placeholder, disabled, showNumber, newline, related} = this.props;
    let popVisible = showNumber || !value.length ? {visible: false} : {};
    return (
      <div
        className={`chooser ${showNumber && 'number-only'} ${disabled && 'chooser-disabled'} ${newline && 'newline'}`}>
        <Popover
          placement="topLeft"
          content={value.map(v => v.label).join("，")}
          getPopupContainer={triggerNode => triggerNode.parentNode}
          {...popVisible}
        >
          <Select
            value={value}
            mode="multiple"
            labelInValue
            placeholder={placeholder}
            onFocus={this.handleFocus}
            dropdownStyle={{display: 'none'}}
            disabled={disabled}
          />
          {value.length && !newline ? (
            <div className={`fake-value-list ${disabled ? 'disabled' : ''}`} onClick={disabled ? () => {} : this.handleFocus}>
              {value.map(v => v.label).join("，")}
            </div>) : ''
          }
        </Popover>
        {/*如果禁用了，就不要后面的清除icon*/}
        {
          disabled ? "" : <Icon className="ant-select-selection__clear" type="close-circle" onClick={this.clear}
                                style={value.length === 0 ? {opacity: 0} : {}}/>
        }
        <div className="chooser-number" onClick={() => {
          !this.props.disabled && this.showList()
        }}>
          {/*已选择 {value.length} 条*/}
          {messages("common.total.selected", {total: value.length === 0 ? '0' : value.length})}
        </div>
        <SelectDepartment visible={showListSelector}
                          onCancel={this.handleListCancel}
                          onOk={this.handleListOk}
                          single={false}
                          related={related}
                          selectedData={selectedList}
                          mode='oid'/>
        <input ref="chooserBlur" style={{position: 'absolute', top: '-9999vh', left: 0, zIndex: -1}}/>
      </div>
    );
  }
}

DepartmentPicker.propTypes = {
  placeholder: React.PropTypes.string,  //输入框空白时的显示文字
  disabled: React.PropTypes.bool,  //是否可用
  type: React.PropTypes.string,  //list选择的type，参见chooserData内
  onChange: React.PropTypes.func,  //进行选择后的回调
  value: React.PropTypes.oneOfType([React.PropTypes.array, React.PropTypes.string]),  //已选择的值，需要传入完整目标数组
  showNumber: React.PropTypes.bool,  //是否只显示'已选XX条'
  newline: React.PropTypes.bool,  //内容是否可换行
  maxNum: React.PropTypes.number,  //最多选择多少条数据
  method: React.PropTypes.string,  //调用方法get/post
  related: React.PropTypes.bool //展示关联开关
};

DepartmentPicker.defaultProps = {
  placeholder: messages("common.please.select"),
  disabled: false,
  listExtraParams: {},
  single: false,
  showNumber: false,
  newline: false,
  method: 'get',
  related: false
};

export default DepartmentPicker;
